package com.swjd.sell.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swjd.sell.dao.OrderDetailDao;
import com.swjd.sell.dao.OrderMasterDao;
import com.swjd.sell.dao.ProductInfoDao;
import com.swjd.sell.dto.OrderDTO;
import com.swjd.sell.dto.StockDTO;
import com.swjd.sell.exception.SellException;
import com.swjd.sell.pojo.OrderDetail;
import com.swjd.sell.pojo.OrderMaster;
import com.swjd.sell.pojo.ProductInfo;
import com.swjd.sell.pojo.enums.OrderStatusEnum;
import com.swjd.sell.pojo.enums.PayStatusEnum;
import com.swjd.sell.pojo.enums.ResultEnum;
import com.swjd.sell.service.OrderService;
import com.swjd.sell.service.ProductInfoService;
import com.swjd.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘涛
 * @create 2021/8/27 22:49
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    protected OrderMasterDao orderMasterDao;
    @Autowired
    protected ProductInfoDao productInfoDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO create(OrderDTO orderDTO) {
        //生成订单id
        String orderId = KeyUtil.genUniqueKey();
        //订单金额
        BigDecimal orderAmount = new BigDecimal(0);
        //订单库存
        ArrayList<StockDTO> stockDTOS = new ArrayList<>();
        //1.查询商品 （数量，价格）
        List<OrderDetail> orderDetails = orderDTO.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            ProductInfo productInfo = productInfoService.selectById(orderDetail.getProductId());
            //判断商品是否存在
            if (productInfo == null) {
                //抛出自定义的异常
                throw new SellException(ResultEnum.PROTECTED_NOT_EXIT);
            }
            //2.订单总金额   商品价格
            orderAmount = productInfo.getProductPrice()
                    //乘商品数量
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    //累加
                    .add(orderAmount);
            //3.写入订单数据库（rderDetail）
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            //将根据传入id查询的商品信息拷贝到订单中
            BeanUtils.copyProperties(productInfo, orderDetail);
            orderDetailDao.insert(orderDetail);
            //存储订购的订单商品id和数量
            StockDTO stockDTO = new StockDTO(productInfo.getProductId(), orderDetail.getProductQuantity());
            stockDTOS.add(stockDTO);
        }
        //3.写入订单数据库（orderMaster）
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getValue());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getValue());
        orderMasterDao.insert(orderMaster);
        //4.扣库存
        productInfoService.reduceStock(stockDTOS);
        return orderDTO;
    }

    @Override
    public OrderDTO selectById(String orderId) {
        OrderMaster orderMaster = orderMasterDao.selectById(orderId);
        if (orderMaster == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        List<OrderDetail> byOrderId = orderDetailDao.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(byOrderId)) {
            throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetails(byOrderId);
        return orderDTO;
    }

    @Override
    public IPage<OrderDTO> selectByBuyerOpenId(String buyerOpenid, Page page) {
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_openid", buyerOpenid);
        IPage<OrderMaster> page1 = orderMasterDao.selectPage(page, queryWrapper);
        //将OrderMaster转化为OrderDTO
        IPage<OrderDTO> orderDTOIPage = new Page<>();
        BeanUtils.copyProperties(page1, orderDTOIPage);
        List<OrderMaster> records = page1.getRecords();
        ArrayList<OrderDTO> orderDTOS = new ArrayList<>();
        for (OrderMaster record : records) {
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(record, orderDTO);
            orderDTOS.add(orderDTO);
        }
        IPage<OrderDTO> orderDTOIPage1 = orderDTOIPage.setRecords(orderDTOS);
        return orderDTOIPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO cancelOrder(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getValue())) {
            log.error("【取消订单】 订单状态不正确，orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderDTO.getOrderId());
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getValue());
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getValue());
        int i = orderMasterDao.updateById(orderMaster);
        if (1 <= 0) {
            log.error("【取消订单】 更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //返还库存
        List<OrderDetail> orderDetails = orderDTO.getOrderDetails();
        ArrayList<StockDTO> stockDTOS = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            StockDTO stockDTO = new StockDTO();
            stockDTO.setProductId(orderDetail.getProductId());
            stockDTO.setProductQuantity(orderDetail.getProductQuantity());
            stockDTOS.add(stockDTO);
        }
        productInfoService.increaseStock(stockDTOS);
        //如果已支付，需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getValue())) {
            //TODO
        }
        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO finishOrder(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getValue())) {
            log.error("【完结订单】 订单状态不正确，orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getValue());
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getValue());
        orderMaster.setOrderId(orderDTO.getOrderId());
        int i = orderMasterDao.updateById(orderMaster);
        if (1 <= 0) {
            log.error("【完结订单】 更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO paidOrder(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getValue())) {
            log.error("【支付订单】 订单状态不正确，orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getValue())) {
            log.error("【支付订单】 支付状态不正确，orderId={},PayStatus={}", orderDTO.getOrderId(), orderDTO.getPayStatus());
            throw new SellException(ResultEnum.PAY_STATUS_ERROR);
        }
        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getValue());
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId(orderDTO.getOrderId());
        orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getValue());
        int i = orderMasterDao.updateById(orderMaster);
        if (1 <= 0) {
            log.error("【支付订单】 更新失败,orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }
}
